<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>淡入淡出</title>

    <style>
        #d {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>

    <div id="d"></div>



</body>

<script>
    var div = document.getElementById('d');

    div.onmouseover = function() {
        Fade(div, 1, -.1, 0);
    }


    div.onmouseout = function() {
        Fade(div, 0, .1, 1);
    }
    var time;

    function Fade(obj, i, speed, tager) {
        clearInterval(time);
        time = setInterval(function() {
            if (i == tager) {
                clearInterval(time);
            } else {
                obj.style.opacity = i;
                i = i + speed;
            }
        }, 30);
    }
</script>

</html>